package com.sduept.nwld.dataserver.controller.equipment.assessment;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;

import com.sduept.bigdata.equipment.assessment.enums.InspectionType;
import com.sduept.bigdata.equipment.assessment.exception.ParameterException;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionExpert;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionItem;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionPlan;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionStation;
import com.sduept.bigdata.equipment.assessment.model.standardlib.StandardInspection;
import com.sduept.bigdata.equipment.assessment.model.template.AssessmentTemplate;
import com.sduept.bigdata.equipment.assessment.service.InspectionExpertService;
import com.sduept.bigdata.equipment.assessment.service.InspectionItemService;
import com.sduept.bigdata.equipment.assessment.service.InspectionPlanService;
import com.sduept.bigdata.equipment.assessment.service.InspectionStationService;
import com.sduept.bigdata.equipment.assessment.service.StandardInspectService;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import com.sduept.permission.cache.PermissionDataCache;
import com.sduept.permission.entity.DepartmentEntityBean;
import com.sduept.permission.entity.PersonnelEntityBean;
import com.sduept.permission.manager.DepartManager;
import com.sduept.utils.PingYinUtil;

/**
 * 新增和编辑评价计划控制器
 * @author pengz
 *
 */
@Named
@ViewScoped
public class AddAssessmentPlanController extends AbstractController{

	private static final long serialVersionUID = -2752025151382574171L;
	@Inject
	private InspectionPlanService service;
//	@Inject
//	private AssessmentTemplateService templateService;
	@Inject
	private InspectionStationService instationService;
	@Inject
	private StandardInspectService standardService;
//	@Inject
//	private CimManager cim;
	@Inject
	private DepartManager dm;
	@Inject
	private InspectionItemService itemService;
	@Inject
	private InspectionExpertService expertService;
//	@Inject
//	private SubstationLedgerManager stationLedgerM;
	
	private InspectionPlan plan;
	/**
	 * 评价类型
	 */
	private String inspectionType;
	/**
	 * 该计划下所有的评价站
	 */
	private Set<InspectionStation> currentInspectionStations = new HashSet<InspectionStation>();
	/**
	 * 已经存在在数据库中的评价厂站
	 */
	private Map<String,InspectionStation> dbInspectionStationMap = new HashMap<String,InspectionStation>();
	/**
	 * 模板id对应的评价厂站集合
	 */
	private Map<String,Set<InspectionStation>> templetIdToInspectionStationsMap = new HashMap<String, Set<InspectionStation>>();
	/**
	 * 已经存在评价条目的变电站集合
	 */
	private List<String> existInspectionItemOfInstationId = new ArrayList<String>();
	/**
	 * 已经存在专家的变电站集合
	 */
	private List<String> existExpertOfInstationId = new ArrayList<String>();
	/**
	 * 当前选中的模板id
	 */
	private String templetId;
	/**
	 * 之前的模板id
	 */
	private String oldTempletId;
	private String title;
	private boolean editPage;
	private List<AssessmentTemplate> templateList;
	
	private AssessmentTemplate selectTemplate;
	/**
	 * 详细区域中评价站根节点
	 */
	private TreeNode inspectionStationsRoot;
	/**
	 * 详细区域中评价站选中节点
	 */
	private TreeNode selectedNode;
	/**
	 * 选中的评价变电站
	 */
	private InspectionStation selectedInspectionStation;
	
	private String expertListColor;
	/**
	 * 负责人选择器根节点
	 */
	private TreeNode responsibleSelectorRoot;
	/**
	 * 负责人选择器选中的节点
	 */
	private TreeNode responsibleSelectedNode;
	/**
	 * 选中的负责人
	 */
	private PersonnelEntityBean selectedResponsible;
	/**
	 * key:负责人首字母
	 * value:负责人名称集合
	 */
	private  Map<String, List<String>> personNameMap;
	private String personName;
	/**
	 * 当前库中所有的负责人集合
	 */
	List<PersonnelEntityBean> personnels;
	/**
	 * 互查信息缓存
	 * key:被评价部门id
	 * value：评价部门id
	 */
	Map<String,String> inspectionOtherMap = new HashMap<String, String>(); 
	/**
	 * 构造代码块初始化
	 */
	{
		plan = new InspectionPlan();
		templateList = new ArrayList<AssessmentTemplate>();
		personnels = new ArrayList<PersonnelEntityBean>();
		personNameMap = new HashMap<>();
	}
	@PostConstruct
	public void init() {
		String[] planIds = getParameters("inspectionPlanIds");
		String planId = "";
		if(planIds!=null) {
			planId = planIds[0];
		}
		if(StringUtils.isNotBlank(planId)) {//计划已经存在
			this.editPage = true;
			this.title = "编辑评价计划";
			plan = service.findById(planId);
			inspectionType = plan.getInspectionType().getValue();
			try {
				currentInspectionStations = instationService.findByInspectionPlan(planId);
				for (InspectionStation instation : currentInspectionStations) {
					dbInspectionStationMap.put(instation.getId(), instation);
				}
			} catch (ParameterException e) {
				System.err.println("评价厂站获取失败！");
			}
		}else {
			this.title = "新增评价计划";
			plan.setId(ObjectId.get().toString());
			plan.setStatus(4);
			plan.setCreator(getCurrentUser().getName());
			plan.setInspectionType(InspectionType.INSPECTIONSELF);
			inspectionType = InspectionType.INSPECTIONSELF.getValue();
		}
		initInspectionStationsRoot(); 
		initResponsibleSelectorRoot();
	}

	/**
	 * 初始化评价的变电站节点树
	 */
	private void initInspectionStationsRoot() {
		inspectionStationsRoot = new LibTreeNode("root", null);
		TreeNode pNode = new LibTreeNode("inspectionPlan",plan,inspectionStationsRoot);
		Map<String, TreeNode> departNodeMap = new HashMap<String,TreeNode>();
		for (InspectionStation inspectionStation : currentInspectionStations) {
			DepartmentEntityBean dept = null;
//			if(inspectionStation.getDepartmentId()!=null) {
//				dept = dm.findDepartmentById(inspectionStation.getDepartmentId());
//			}
			if(dept!=null) {
//				if(!inspectionOtherMap.containsKey(dept.getId())) {
//					inspectionOtherMap.put(dept.getId(), inspectionStation.getInspectionDepartment());
//				}
				if(!departNodeMap.containsKey(dept.getId())) {
					LibTreeNode departNode = new LibTreeNode("department", dept, pNode);
					departNodeMap.put(dept.getId(), departNode);
				}			
				TreeNode deptNode = departNodeMap.get(dept.getId());
				LibTreeNode instationNode = new LibTreeNode("inspectionStation", inspectionStation, deptNode);
				if(selectedInspectionStation!=null&&selectedInspectionStation.getId().equals(inspectionStation.getId())) {
					deptNode.setExpanded(true);
					instationNode.setSelected(true);
				}
			}
		}
		pNode.setExpanded(true);     
	}
	/**
	 * 初始化负责人选择器根节点
	 */
	private void initResponsibleSelectorRoot() {
		responsibleSelectorRoot = new LibTreeNode("Root", null);
		List<DepartmentEntityBean> roots = dm.findRootDepts();
		for (DepartmentEntityBean department : roots) {
			TreeNode orgRoot = new LibTreeNode("dept", department, responsibleSelectorRoot);
			List<DepartmentEntityBean> ds = dm.getDepartmentsByParent(department.getId()); // 默认展开一级
			for (DepartmentEntityBean department1 : ds) {
				 new LibTreeNode("dept", department1, orgRoot);
			}
			List<PersonnelEntityBean> ps = dm.findDeptPersonnels(department.getId());
			for (PersonnelEntityBean personnel : ps) {
				new DefaultTreeNode("personnel", personnel, orgRoot);
			}
			orgRoot.setExpanded(true);
		}
		personnels.clear();
		personnels.addAll(PermissionDataCache.getInstance().getPersonMap().values());
		initPersonNameMap();
	}
	/**
	 * 初始化personNameMap
	 */
	private void initPersonNameMap() {
		personNameMap.clear();
		for (PersonnelEntityBean personnelEntityBean : personnels) {
			String key  = PingYinUtil.getPingYinHeader(personnelEntityBean.getName());
			List<String> value =personNameMap.get(key);
			if(value==null) {
				value = new ArrayList<String>();
				personNameMap.put(key, value);
			}
			value.add(personnelEntityBean.getName());
		}
	}
	/**
	 * 处理负责人选取器选中事件
	 * @param event
	 */
	public void onResponsibleNodeSelect(NodeSelectEvent event) {
		responsibleSelectedNode = event.getTreeNode();
		if ("personnel".equals(responsibleSelectedNode.getType())) {
	        selectedResponsible = (PersonnelEntityBean) responsibleSelectedNode.getData();
		}
	}
	/**
	 * 组织机构树展开
	 * @param event
	 */
	public void onResponsibleNodeExpand(NodeExpandEvent event) {
		if(StringUtils.isBlank(personName)) {
			TreeNode node = event.getTreeNode();
			node.getChildren().clear();
			DepartmentEntityBean dept = (DepartmentEntityBean) node.getData();
			List<DepartmentEntityBean> ds = dm.getDepartmentsByParent(dept.getId());
			for (DepartmentEntityBean d : ds) {
				 new LibTreeNode("dept", d, node);
			}
			List<PersonnelEntityBean> personnels = dm.findDeptPersonnels(dept.getId());
			if (personnels != null && personnels.size() > 0) {
				for (PersonnelEntityBean p : personnels) {
					new DefaultTreeNode("personnel", p, node);
				}
			}
		}
	}

	public List<String> completeResponsibles(String query) {
		List<String> responsibles = new ArrayList<String>();
		for (String s : personNameMap.keySet()) {
			if(s.startsWith(query)) {
				responsibles.addAll(personNameMap.get(s));
			}
		}
		return responsibles;
	}
	/**
     * 组织机构树查人
     * @param event
     */
    public  void autoCompleteOrgTree(SelectEvent event) {
    	Object item = event.getObject();
		if (null != item) {
			filterTree(item.toString());
		}
    }
    /**
     * 根据查询内容重新展示组织机构树
     * @param name
     */
	private void filterTree(String name) {
		for (PersonnelEntityBean person : personnels) {
			if(person.getName().equals(name)) {
				selectedResponsible = person;
				break;
			}
		}
		DepartmentEntityBean selectDept = dm.findPersonDepart(selectedResponsible.getCode());//查到人就结束 然后一直递归到根
		responsibleSelectorRoot = new LibTreeNode("Root", null);//递归查询父部门 直到父部门为根部门  
		LibTreeNode pNode = new LibTreeNode("dept", selectDept, getParentDept(selectDept,responsibleSelectorRoot));
		TreeNode node = new DefaultTreeNode("personnel", selectedResponsible,pNode);
		pNode.setExpanded(true);
		node.setSelected(true);
	}
	 /**
               * 获得父部门  --组织机构树
     * @param selectDept
     * @param root2
     * @return
     */
	private TreeNode getParentDept(DepartmentEntityBean selectDept, TreeNode root2) {
		DepartmentEntityBean  parentDept = selectDept.getParent();
		TreeNode treeNode = null;
		if(parentDept.getParent()!=null) {
			treeNode  = new LibTreeNode("dept", parentDept,getParentDept(parentDept,root2));
			treeNode.setExpanded(true);
		}else {
			treeNode  = new LibTreeNode("dept", parentDept,root2);
			treeNode.setExpanded(true);
		}
		return treeNode;
	}
	/**
	 * 刷新责任人选取器搜索框
	 */
	public void refresh() {
		personName = "";
		selectedResponsible = null;
		responsibleSelectedNode = null;
		initResponsibleSelectorRoot();
	}
	/**
	 * 保存选择的责任人
	 */
	public void saveResponsible() {
		plan.setResponsible(selectedResponsible.getName());
	}
	
	/**
	 * 保存为草稿
	 */
	public void saveAssessmentPlan() {
		if(StringUtils.isBlank(plan.getName())) {
			alertErrorMessage("计划名称不能为空");
			return;
		}
		//先保存该计划
		plan = service.createOrupdate(plan);
		//另开一个线程保存评价厂站及评价项
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for(InspectionStation instation : currentInspectionStations) {
					instationService.update(instation);
					if(dbInspectionStationMap.containsKey(instation.getId())) {
						dbInspectionStationMap.remove(instation.getId());
					}
				}
				//从数据库中删除取消掉的评价厂站
				try {
					for(String instationId : dbInspectionStationMap.keySet()) {
						instationService.deleteById(instationId);
					}
				} catch (ParameterException e) {
					System.err.println("评价厂站删除失败！");
				}
				plan.setStatus(0);
				service.createOrupdate(plan);
			}
		}).start();
		PrimeFaces.current().dialog().closeDynamic(null);
	}
	/**
	 * 重置
	 */
	public void clearData() {
		plan.setName(null);
		plan.setStartTime(null);
		plan.setEndTime(null);
		plan.setResponsible(null);
	}
	
	/**
	 * 处理评价类型改变
	 */
	public void handleTypeChange(int remark) {
		if(remark==1) {
			if(inspectionType.equals(InspectionType.INSPECTIONSELF.getValue())) {
				inspectionType = InspectionType.INSPECTIONOTHER.getValue();
				plan.setInspectionType(InspectionType.INSPECTIONOTHER);
			}else {
				inspectionType = InspectionType.INSPECTIONSELF.getValue();
				plan.setInspectionType(InspectionType.INSPECTIONSELF);
			}
			//清空已选评价厂站信息
			currentInspectionStations.clear();
			initInspectionStationsRoot();
		}
	}
	public void handleTypeChange() {
		if(currentInspectionStations.isEmpty()) {
			
		}else {
			PrimeFaces.current().executeScript("openAlertDialog()");
		}
	}
	/**
	 * 将由templateItem转换的inspectionItem集合 变成 我所需要的保存到inspectionStation中的集合
	 * @param rootStand
	 * @param standIdToInsItemMap
	 * @param needInspectionItems
	 * @return
	 */
	private boolean expand(StandardInspection pStand,Map<String, InspectionItem> standIdToInsItemMap, List<InspectionItem> needInspectionItems) {
		boolean expand = false;
		List<StandardInspection> children = standardService.findByParentId(pStand.getId());
		if(children!=null&&children.size()>0) {
			boolean hasFalse = false;
			for(StandardInspection stand : children) {
				boolean exist = expand(stand,standIdToInsItemMap,needInspectionItems);
				if(exist) {
					needInspectionItems.add(standIdToInsItemMap.get(stand.getId()));
				}else {
					hasFalse = true;
				}
			}
			if(!hasFalse) {
				expand = true;
			}
		}else {
			if(standIdToInsItemMap.containsKey(pStand.getId())) {
				expand = true;
			}
		}
		
		return expand;
		
	}

	/**
	 * 选择树节点
	 * @param event
	 */
	public void onNodeSelect(NodeSelectEvent event) {
		selectedNode = event.getTreeNode();
		if(selectedNode.getData() instanceof InspectionPlan) {
			// 选中的是评价计划节点
			selectedInspectionStation = null;
		} else if(selectedNode.getData() instanceof InspectionStation) {
			// 选中的是变电站节点
			selectedInspectionStation = (InspectionStation) selectedNode.getData();	
		}else {
			selectedInspectionStation = null;
		}
	}
	/**
	 * 保存评价站编辑信息
	 */
	public void saveInspectionStationEdit() {
		initInspectionStationsRoot();
		addSuccessMessage("修改成功！");
	}

	/**
	 * 打开评价标准多选择框
	 */
	public void openStandardSelectorDialog() {
        Map<String, Object> options = new HashMap<String, Object>();
		options.put("resizable", true);
		options.put("draggable", true);
		options.put("modal", true);
		options.put("width", 620);
		options.put("height", 650);
		Map<String, List<String>> params = new HashMap<>();
		List<String> lt = new ArrayList<String>();
		try {
			List<InspectionItem> items = new ArrayList<InspectionItem>();
			if(!existInspectionItemOfInstationId.contains(selectedInspectionStation.getId())) {
				items = instationService.findInspectionItemByStationId(selectedInspectionStation.getId());
				selectedInspectionStation.setInspectionItems(items);
				existInspectionItemOfInstationId.add(selectedInspectionStation.getId());
			}else {
				items = selectedInspectionStation.getInspectionItems();
			}
			Map<String,InspectionItem> standIdToInsItemMap = new HashMap<String,InspectionItem>();
			List<InspectionItem> needInspectionItems = new ArrayList<InspectionItem>();
			for(InspectionItem item:items) {
				standIdToInsItemMap.put(item.getStandardId(), item);
			}
			StandardInspection rootStand = null;
			try {
				List<StandardInspection> standardRoots = standardService.findAvailableRoot();
				if(standardRoots!=null&&standardRoots.size()>0) {
					rootStand = standardRoots.get(0);
				}
				expand(rootStand,standIdToInsItemMap,needInspectionItems);
			} catch (Exception e) {
				e.printStackTrace();
			}
			for(InspectionItem item:needInspectionItems) {
				lt.add(item.getStandardId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		params.put("selectedStands", lt);
		PrimeFaces.current().dialog().openDynamic("/ui/common/standard_selector_multiple.xhtml",  options,params);
    }
	/**
	 * 添加stand评价标准所有的子标准（转换成评价条目）到insItems中
	 * @param stand
	 * @param pItem
	 * @param insItems
	 * @param standToInsItemMap
	 * @param selectedInspectionStation2
	 * @throws ParameterException
	 */
	private void addChildrenStand(StandardInspection stand,InspectionItem pItem,List<InspectionItem> insItems, Map<String, InspectionItem> standToInsItemMap, InspectionStation selectedInspectionStation2) throws ParameterException {
		if(standToInsItemMap.containsKey(stand.getId())) {
			return;
		}
		InspectionItem item = itemService.convertFromStandardInspection(stand.getId(),plan.getId());
		item.setParent(pItem);
		item.setStatus(0);
		item.setStation(selectedInspectionStation2);
		List<StandardInspection> childrenStand = standardService.findByParentId(stand.getId());
		if(childrenStand!=null&&childrenStand.size()>0) {
			for (StandardInspection standardInspection : childrenStand) {
				addChildrenStand(standardInspection,item,insItems,standToInsItemMap,selectedInspectionStation2);
			}
		}
		insItems.add(item);
		standToInsItemMap.put(stand.getId(), item);
	}
	/**
	 * 找到standardInspection评价标准的父标准，并转换成评价条目
	 * @param standardInspection
	 * @param insItems
	 * @param pInsItemMap
	 * @param selectedInspectionStation2
	 * @return
	 * @throws ParameterException
	 */
	private InspectionItem getParentInsItem(StandardInspection standardInspection, List<InspectionItem> insItems, Map<String, InspectionItem> pInsItemMap, InspectionStation selectedInspectionStation2) throws ParameterException {
		InspectionItem item = null;
		StandardInspection pstand = standardInspection.getParent();
		if(pstand!=null) {
			if(pInsItemMap.containsKey(pstand.getId())) {
				return pInsItemMap.get(pstand.getId());
			}else {
				item = itemService.convertFromStandardInspection(pstand.getId(),plan.getId());
				item.setParent(getParentInsItem(pstand,insItems,pInsItemMap,selectedInspectionStation2));
				item.setStatus(0);
				item.setStation(selectedInspectionStation2);
				insItems.add(item);
				pInsItemMap.put(pstand.getId(), item);
			}
		}
		return item;
	}
	/**
	 * 编辑模板项的评价标准
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	public void onStandardsChosenWhenEdit(SelectEvent event) {
		// 选中的标准评价项目
		List<StandardInspection> allStandards = (List<StandardInspection>) event.getObject();
		if(null == allStandards) {
			addErrorMessage("请选择评价项目");
			return ;
		}
		try {
			//instationService.deleteById(selectedInspectionStation.getId());
			currentInspectionStations.remove(selectedInspectionStation);
			Map<String,InspectionItem> standToInsItemMap = new HashMap<String,InspectionItem>();
			Map<String,InspectionItem> pInsItemMap = new HashMap<String,InspectionItem>();
			List<InspectionItem> insItems = new ArrayList<InspectionItem>();
			for (StandardInspection standardInspection : allStandards) {
				InspectionItem pInsItem = getParentInsItem(standardInspection,insItems,pInsItemMap,selectedInspectionStation);
				addChildrenStand(standardInspection,pInsItem,insItems,standToInsItemMap,selectedInspectionStation);
			}
			//重新设置评价条目
			selectedInspectionStation.setInspectionItems(insItems);
			//instationService.createOrUpdate(selectedInspectionStation);	
			currentInspectionStations.add(selectedInspectionStation);
		} catch (ParameterException e1) {
			e1.printStackTrace();
		}
			
	}
	/**
	 * 打开专家评价标准选择框
	 */
	public void openExpertSelectorDialog() {
//		Map<String, Object> options = new HashMap<String, Object>();
//		options.put("resizable", true);
//		options.put("draggable", true);
//		options.put("modal", true);
//		options.put("width", 620);
//		options.put("height", 650);
//		Map<String, List<String>> params = new HashMap<>();
//		List<String> expertCodes = new ArrayList<String>();
//		Set<InspectionExpert> experts = selectedInspectionStation.getExperts();
//		if(experts!=null&&!experts.isEmpty()) {
//			for (InspectionExpert expert : experts) {
//				expertCodes.add(expert.getCode());
//			}
//		}				
//		params.put("experts", expertCodes);
//		PrimeFaces.current().dialog().openDynamic("/ui/common/expert_selector_multiple.xhtml",  params,options);
	}
	/**
	 * 
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	public void onExpertsChosen(SelectEvent event) {
//		List<InspectionExpert> experts = (List<InspectionExpert>) event.getObject();
//		if(null == experts) {
//			addErrorMessage("请选择专家");
//			return ;
//		}
//		Set<InspectionExpert> currentExperts = selectedInspectionStation.getExperts();
//		Map<String, InspectionExpert> currentExpertMap = new HashMap<String,InspectionExpert>();
//		if(currentExperts!=null) {
//			for (InspectionExpert inspectionExpert : currentExperts) {
//				currentExpertMap.put(inspectionExpert.getId(), inspectionExpert);
//			}
//		}
//		for(InspectionExpert expert : experts) {
//			if(currentExpertMap.containsKey(expert.getId())) {//已存在
//				currentExpertMap.remove(expert.getId());
//			}else {//重新选取的
//				currentExperts.add(expert);
//			}
//		}
//		for(String expertId : currentExpertMap.keySet()) {//取消掉的专家
//			currentExperts.remove(currentExpertMap.get(expertId));
//		}
	}
	/**
	 * 获取选中变电站的专家集合，并连接成字符串返回
	 */
	public String getExpertsStr() {
		StringBuffer result = new StringBuffer();
		if(selectedInspectionStation!=null) {
//			Set<InspectionExpert> currentExperts = selectedInspectionStation.getExperts();
			Set<InspectionExpert> currentExperts = null;
			if(currentExperts!=null&&!currentExperts.isEmpty()) {
				for (InspectionExpert expert : currentExperts) {
					result.append(expert.getName()+" ");
				}
			}
		}
		return result.toString();
	}
	/**
	 * 打开添加评价站信息弹窗
	 */
	public void openAddInspectionStationSelectorDialog() {
		Map<String, Object> options = new HashMap<String, Object>();
		options.put("resizable", true);
		options.put("draggable", true);
		options.put("modal", true);
		options.put("width", 800);
		options.put("height", 720);
		Map<String, List<String>> params = new HashMap<>();
		List<String> dates = new ArrayList<String>();
		SimpleDateFormat format = new SimpleDateFormat();
		if(plan.getStartTime()!=null) {
			dates.add(format.format(plan.getStartTime()));
		}else {
			dates.add("");
		}
		if(plan.getEndTime()!=null) {
			dates.add(format.format(plan.getEndTime()));
		}else {
			dates.add("");
		}
		params.put("dates", dates);
		List<String> stationIds = new ArrayList<String>();
		if(currentInspectionStations!=null&&!currentInspectionStations.isEmpty()) {
			for(InspectionStation instation : currentInspectionStations) {
				stationIds.add(instation.getStationId());
			}
		}
		params.put("stationIds", stationIds);
		List<String> inspectionType = new ArrayList<String>();
		inspectionType.add(this.inspectionType);
		params.put("inspectionType", inspectionType);
		List<String> planId = new ArrayList<String>();
		planId.add(this.plan.getId());
		params.put("planId", planId);
		List<String> inspectionOtherList = new ArrayList<String>();
		for(String deptId : inspectionOtherMap.keySet()) {
			inspectionOtherList.add(deptId+"-"+inspectionOtherMap.get(deptId));
		}
		params.put("inspectionOtherList", inspectionOtherList);
		PrimeFaces.current().dialog().openDynamic("/ui/equipmentAssessment/assessmentplan/dialog/inspectionStation_selector_stepbystep.xhtml",  options,params);
	}
	/**
	 * 
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	public void onInspectionStationChosen(SelectEvent event) {
		Set<InspectionStation> instations = (Set<InspectionStation>) event.getObject();
		for (InspectionStation instation : instations) {
			instation.setInspectPlan(plan);
			Iterator<InspectionStation> it = currentInspectionStations.iterator();
			while(it.hasNext()) {
				InspectionStation station = it.next();
				if(station.getStationId().equals(instation.getStationId())) {
					it.remove();
				}
			}
			currentInspectionStations.add(instation);
			if(!existExpertOfInstationId.contains(instation.getId())) {
				existExpertOfInstationId.add(instation.getId());
			}
			if(!existInspectionItemOfInstationId.contains(instation.getId())) {
				existInspectionItemOfInstationId.add(instation.getId());
			}
		}
		initInspectionStationsRoot();
	}
	/**
	 * 
	 */
	public void openSelectFromTemplate() {
		Map<String, Object> options = new HashMap<String, Object>();
		options.put("resizable", true);
		options.put("draggable", true);
		options.put("modal", true);
		options.put("width", 800);
		options.put("height", 720);
		Map<String, List<String>> params = new HashMap<>();
		List<String> dates = new ArrayList<String>();
		SimpleDateFormat format = new SimpleDateFormat();
		if(plan.getStartTime()!=null) {
			dates.add(format.format(plan.getStartTime()));
		}else {
			dates.add("");
		}
		if(plan.getEndTime()!=null) {
			dates.add(format.format(plan.getEndTime()));
		}else {
			dates.add("");
		}
		params.put("dates", dates);
		List<String> inspectionType = new ArrayList<String>();
		inspectionType.add(this.inspectionType);
		params.put("inspectionType", inspectionType);
		List<String> planId = new ArrayList<String>();
		planId.add(this.plan.getId());
		params.put("planId", planId);
		PrimeFaces.current().dialog().openDynamic("/ui/equipmentAssessment/assessmentplan/dialog/selectFromTemplateDialog.xhtml",  options,params);
	}
	/**
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void onInspectionStationChosenFromTemplate(SelectEvent event) {
		Map<String,Set<InspectionStation>> templateToInspectionStations = (Map<String, Set<InspectionStation>>) event.getObject();
		for(String templateId : templateToInspectionStations.keySet()) {
			for(InspectionStation instation : templateToInspectionStations.get(templateId)) {
				boolean bool = true;
				label1:for(InspectionStation station : currentInspectionStations) {
					if(station.getId().equals(instation.getId())) {
						bool = false;
						break label1;
					}
				}
				if(bool) {
					instation.setInspectPlan(plan);
					currentInspectionStations.add(instation);
				}
				if(!existExpertOfInstationId.contains(instation.getId())) {
					existExpertOfInstationId.add(instation.getId());
				}
				if(!existInspectionItemOfInstationId.contains(instation.getId())) {
					existInspectionItemOfInstationId.add(instation.getId());
				}
			}
		}
		initInspectionStationsRoot();
	}
	/**
	 * 删除选中的变电站节点
	 */
	public void deleteSelectedInspectionStation() {
		if(selectedNode.getData() instanceof InspectionPlan) {
			currentInspectionStations.clear();	
			addSuccessMessage("删除成功！");
		} else if(selectedNode.getData() instanceof InspectionStation) {
			// 选中的是变电站节点
			TreeNode pNode = selectedNode.getParent();
			pNode.getChildren().remove(selectedNode);
			if(pNode.getChildren().size()<=0) {
				pNode.getParent().getChildren().remove(pNode);
			}			
			currentInspectionStations.remove(selectedInspectionStation);
			addSuccessMessage("删除成功！");
		}else {
			List<TreeNode> instationNodes = selectedNode.getChildren();
			if(instationNodes!=null&&instationNodes.size()>0) {
				for (TreeNode instationNode : instationNodes) {
					InspectionStation instation = (InspectionStation) instationNode.getData();
					currentInspectionStations.remove(instation);
				}
				addSuccessMessage("删除成功！");
			}
			selectedNode.getParent().getChildren().remove(selectedNode);
		}
		this.selectedNode = null;
		this.selectedInspectionStation = null;
	}
	/**
	 * 处理评价开始时间选中事件
	 */
	public void handleStartTime() {
		Map<String, Date> result = getStartAndEndTime();
		Date start = result.get("start");
		Date end = result.get("end");
		if(plan.getEndTime()!=null&&dateCompare(plan.getStartTime(),plan.getEndTime())==1) {
			plan.setStartTime(null);
			addErrorMessage("评价计划开始时间不应大于评价计划的结束时间，请重新选择");
			return;
		}
		if(start!=null) {
			if(dateCompare(start,plan.getStartTime())==-1) {
				plan.setStartTime(null);
				addErrorMessage("评价计划开始时间不应大于评价站的开始时间，请重新选择");
				return;
			}
		}else {
			if(end!=null&&dateCompare(end,plan.getStartTime())==-1) {
				plan.setStartTime(null);
				addErrorMessage("评价计划开始时间不应大于评价站的结束时间，请重新选择");
				return;
			}
		}
	}
	/**
	 * 处理评价结束时间选中事件
	 */
	public void handleEndTime() {
		Map<String, Date> result = getStartAndEndTime();
		Date start = result.get("start");
		Date end = result.get("end");
		if(plan.getStartTime()!=null&&dateCompare(plan.getStartTime(),plan.getEndTime())==1) {
			plan.setEndTime(null);
			addErrorMessage("评价计划结束时间不应小于评价计划的开始时间，请重新选择");
			return;
		}
		if(end!=null) {
			if(dateCompare(end,plan.getEndTime())==1) {
				plan.setEndTime(null);
				addErrorMessage("评价计划结束时间不应小于评价站的结束时间，请重新选择");
				return;
			}
		}else {
			if(start!=null&&dateCompare(start,plan.getEndTime())==1) {
				plan.setEndTime(null);
				addErrorMessage("评价计划结束时间不应小于评价站的开始时间，请重新选择");
				return;
			}
		}
	}
	/**
	 * 获取该评价计划下评价站的评价时间的起始时间和终止时间
	 * @return
	 */
	private Map<String,Date> getStartAndEndTime() {
		Map<String,Date> result = new HashMap<String, Date>();
		Date start = null;
		Date end = null;
		if(!currentInspectionStations.isEmpty()) {
			for (InspectionStation inspectionStation : currentInspectionStations) {
				if(start==null) {
					start = inspectionStation.getStartTime();
				}else {
					if(inspectionStation.getStartTime()!=null&&dateCompare(start,inspectionStation.getStartTime())==1) {
						start = inspectionStation.getStartTime();
					}
				}
				if(end==null) {
					end = inspectionStation.getEndTime();
				}else {
					if(inspectionStation.getEndTime()!=null&&dateCompare(end,inspectionStation.getEndTime())==-1) {
						end = inspectionStation.getEndTime();
					}
				}
			}
		}
		result.put("start", start);
		result.put("end", end);
		return result;
	}
	/**
	 * 比较日期
	 * 注意：仅比较年月日
	 * @param date1
	 * @param date2
	 * @return date1>date2 -> 1; date1<date2 -> -1; date1=date2 ->0
	 */
	private int dateCompare(Date date1, Date date2) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dateFirst = null;
        try {
            dateFirst = dateFormat.parse(dateFormat.format(date1));
            Date dateLast = dateFormat.parse(dateFormat.format(date2));

        if (dateFirst.after(dateLast)) {
            return 1;
        } else if (dateFirst.before(dateLast)) {
            return -1;
        }
        return 0;
        } catch (ParseException e) {
            return 0;
        }
    }
	
	/**
	 * 将专家集合转成字符串输出
	 * 注意：最多输出前两个专家，之后用...代替
	 * @param instation
	 * @return
	 */
	public String getExpertListStr(InspectionStation instation) {
		int index=0;
		String result = "";
		Set<InspectionExpert> experts = new HashSet<InspectionExpert>();
		if(!existExpertOfInstationId.contains(instation.getId())) {
//			try {
//				experts = expertService.findByInspectionStation(instation.getId());
//			} catch (ParameterException e) {
//				System.err.println("获取专家异常！");
//			}
//			instation.setExperts(experts);
			existExpertOfInstationId.add(instation.getId());
		}else {
//			experts = instation.getExperts();
		}
		if(!experts.isEmpty()) {
			for (InspectionExpert expert : experts) {
				if(index>1) {
					result = result.trim();
					result+="...";
					break;
				}
				result+=expert.getName()+" ";
				index++;				
			}
			expertListColor = "blue";
		}else {
			result = "未选择专家";
			expertListColor = "red";
		}
		
		return result;
	}
	
	public InspectionPlan getPlan() {
		return plan;
	}
	public void setPlan(InspectionPlan plan) {
		this.plan = plan;
	}
	public String getTempletId() {
		return templetId;
	}
	public void setTempletId(String templetId) {
		this.templetId = templetId;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
	public AssessmentTemplate getSelectTemplate() {
		return selectTemplate;
	}
	public void setSelectTemplate(AssessmentTemplate selectTemplate) {
		this.selectTemplate = selectTemplate;
	}
	public TreeNode getInspectionStationsRoot() {
		return inspectionStationsRoot;
	}
	public void setInspectionStationsRoot(TreeNode inspectionStationsRoot) {
		this.inspectionStationsRoot = inspectionStationsRoot;
	}
	public List<AssessmentTemplate> getTemplateList() {
		return templateList;
	}
	public void setTemplateList(List<AssessmentTemplate> templateList) {
		this.templateList = templateList;
	}
	public boolean isEditPage() {
		return editPage;
	}
	public void setEditPage(boolean editPage) {
		this.editPage = editPage;
	}
	public TreeNode getSelectedNode() {
		return selectedNode;
	}
	public void setSelectedNode(TreeNode selectedNode) {
		this.selectedNode = selectedNode;
	}
	public InspectionStation getSelectedInspectionStation() {
		return selectedInspectionStation;
	}
	public void setSelectedInspectionStation(InspectionStation selectedInspectionStation) {
		this.selectedInspectionStation = selectedInspectionStation;
	}

	public String getExpertListColor() {
		return expertListColor;
	}

	public void setExpertListColor(String expertListColor) {
		this.expertListColor = expertListColor;
	}
	public TreeNode getResponsibleSelectorRoot() {
		return responsibleSelectorRoot;
	}
	public void setResponsibleSelectorRoot(TreeNode responsibleSelectorRoot) {
		this.responsibleSelectorRoot = responsibleSelectorRoot;
	}
	public TreeNode getResponsibleSelectedNode() {
		return responsibleSelectedNode;
	}
	public void setResponsibleSelectedNode(TreeNode responsibleSelectedNode) {
		this.responsibleSelectedNode = responsibleSelectedNode;
	}
	public PersonnelEntityBean getSelectedResponsible() {
		return selectedResponsible;
	}
	public void setSelectedResponsible(PersonnelEntityBean selectedResponsible) {
		this.selectedResponsible = selectedResponsible;
	}
	public Map<String, List<String>> getPersonNameMap() {
		return personNameMap;
	}
	public void setPersonNameMap(Map<String, List<String>> personNameMap) {
		this.personNameMap = personNameMap;
	}
	public List<PersonnelEntityBean> getPersonnels() {
		return personnels;
	}
	public void setPersonnels(List<PersonnelEntityBean> personnels) {
		this.personnels = personnels;
	}
	public String getPersonName() {
		return personName;
	}
	public void setPersonName(String personName) {
		this.personName = personName;
	}
	public Set<InspectionStation> getCurrentInspectionStations() {
		return currentInspectionStations;
	}
	public void setCurrentInspectionStations(Set<InspectionStation> currentInspectionStations) {
		this.currentInspectionStations = currentInspectionStations;
	}
	public Map<String, Set<InspectionStation>> getTempletIdToInspectionStationsMap() {
		return templetIdToInspectionStationsMap;
	}
	public void setTempletIdToInspectionStationsMap(Map<String, Set<InspectionStation>> templetIdToInspectionStationsMap) {
		this.templetIdToInspectionStationsMap = templetIdToInspectionStationsMap;
	}
	public String getOldTempletId() {
		return oldTempletId;
	}
	public void setOldTempletId(String oldTempletId) {
		this.oldTempletId = oldTempletId;
	}
	public Map<String, InspectionStation> getDbInspectionStationMap() {
		return dbInspectionStationMap;
	}
	public void setDbInspectionStationMap(Map<String, InspectionStation> dbInspectionStationMap) {
		this.dbInspectionStationMap = dbInspectionStationMap;
	}
	public String getInspectionType() {
		return inspectionType;
	}
	public void setInspectionType(String inspectionType) {
		this.inspectionType = inspectionType;
	}
}
